package rainy.file.synchronization.client.file.traverse;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;

import org.apache.commons.codec.digest.DigestUtils;

/**
 * 获取文件的hash值,如果为文件夹则返回null
 * 
 * @author dongwenbin
 *
 */
public class FileHasher {

	public static String generateFileHash(String file) {
		File _f = new File(file);
		return generateFileHash(_f);
	}

	public static String generateFileHash(File file) {
		try (RandomAccessFile raf = new RandomAccessFile(file, "r")) {
			long length = raf.length();
			byte[] _b = new byte[200];
			if (length > 200) {
				raf.read(_b, 0, 100);
				byte[] _bb = new byte[100];
				raf.seek(Integer.valueOf(String.valueOf(length)) - 101);
				raf.read(_bb);
				for (int i = 0; i < 100; i++) {
					_b[i + 100] = _bb[i];
				}
			} else {
				raf.read(_b);
			}
			return doHash(_b);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	private static String doHash(byte[] bytes) {
		return DigestUtils.md2Hex(bytes);
	}
}
